package com.xhai.common.utils.i18n;

import com.xhai.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;

/**
 * @author xhai
 * @description 获取i18n资源文件
 * @date 2025/5/30
 */
@Slf4j
public class MessageUtils {
    /**
     * 根据消息键和参数 获取消息 委托给spring messageSource
     *
     * @param code 消息键
     * @param args 参数
     * @return 获取国际化翻译值
     */
    public static String message(String code, Object... args) {
        MessageSource messageSource = SpringUtils.getBean(MessageSource.class);
        try {
            return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());
        } catch (NoSuchMessageException e) {
            log.error(e.getMessage(), e);
            StringBuilder builder = new StringBuilder();
            builder.append(code);
            if (args != null && args.length > 0) {
                builder.append(" ");
                for (int i = 0; i < args.length; i++) {
                    builder.append("args[").append(i).append("]=").append(args[i]);
                    if (i < args.length - 1) {
                        builder.append(",");
                    }
                }
            }

            return builder.toString();
        }
    }
}
